package com.demo.springBootDemo05.web;

import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.demo.springBootDemo05.entity.User;
import com.demo.springBootDemo05.utils.CommonResult;

@RestController
@RequestMapping("/user")
public class UserController {

	@RequestMapping(method = RequestMethod.GET)
	public Object users() {
		CommonResult<List<User>> result = new CommonResult<>();
		result.setData(User.listUser());
		return result;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Object id(@PathVariable("id") Integer id) {
		CommonResult<User> result = new CommonResult<>();
		result.setData(User.getUser(id));
		return result;
	}

	@RequestMapping(value = "", method = RequestMethod.POST)
	public Object add(@RequestBody User user) {
		CommonResult<User> result = new CommonResult<>();
		result.setData(User.addUser(user.getUsername(), user.getPassword()));
		return result;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	// PUT请求:Form表单不支持Put方法,使用@RequestBody接收参数
	public Object update(@PathVariable("id") Integer id, @RequestBody User user) {
		CommonResult<User> result = new CommonResult<>();
		result.setData(User.updateUser(id, user.getUsername(), user.getPassword()));
		return result;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public Object delete(@PathVariable("id") Integer id) {
		CommonResult<User> result = new CommonResult<>();
		result.setData(User.deleteUser(id));
		return result;
	}

}
